package com.gray.pool.general;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created on 2018/11/30.
 * <p>
 * 当前线程池，会自定义线程配置。
 * 并在没有任务执行后关闭线程池，新任务进来会自动实例一个新的线程池。
 *
 * @author grayCat
 * @since 1.0
 */
@Component
public class CommonThreadPool {

    /**
     * 通用线程池
     * @return
     */
    @Bean
    public ThreadPoolExecutor sampleExecutor() {
        int poolSize = Runtime.getRuntime().availableProcessors() + 1;
        int coreSize = poolSize < 4 ? poolSize : 4;
        ThreadPoolExecutor sampleService = new ThreadPoolExecutor(
                coreSize,
                poolSize,
                    10L,
                    TimeUnit.SECONDS,
                    new ArrayBlockingQueue<Runnable>(40));
        return sampleService;
    }

    /**
     * 需求不算特别大的线程池
     * @return
     */
    @Bean
    public ThreadPoolExecutor executorService() {
        int poolSize = Runtime.getRuntime().availableProcessors() + 1;
        ThreadPoolExecutor executorService = new ThreadPoolExecutor(
                    poolSize,
                    poolSize,
                    0L,
                    TimeUnit.SECONDS,
                    new ArrayBlockingQueue<Runnable>(800));
        return executorService;
    }
}
